package net.sdd.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sdd.school.entity.Chapter;
import net.sdd.school.entity.Video;
import net.sdd.school.entity.vo.ChapterVo;
import net.sdd.school.entity.vo.VideoVo;
import net.sdd.school.mapper.ChapterMapper;
import net.sdd.school.service.IChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sdd.school.service.IVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2022-08-23
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements IChapterService {
    @Autowired
    private IVideoService videoService;

    @Override
    public List<ChapterVo> findChapterAndVideo(String courseId) {
        //1. 根据课程id查询章节
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<Chapter> chapterList = list(wrapper);

        //2. 根据课程id查询视频
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<Video> videoList = videoService.list(videoWrapper);

        //3. 封装结果: 封装vo；给每一个章节设置视频信息
        List<ChapterVo> voList = chapterList.stream().map(chapter -> {
            //3.1 创建vo对象
            ChapterVo chapterVo = new ChapterVo();
            //3.2 封装章节信息
            BeanUtils.copyProperties(chapter,chapterVo);
            //3.3 封装视频信息: 给每一个章节封装对应的视频信息
            //3.3.1 获取章节的id
            String id = chapter.getId();
            //3.3.3 遍历视频集合, 封装视频vo集合
            List<VideoVo> videoVoList = new ArrayList<>();
            videoList.forEach(video -> {
                if (id.equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVoList.add(videoVo);
                }
            });
            //3.4 把视频集合设置到章节中。一个章节下，对应多个视频
            chapterVo.setChildren(videoVoList);

            return chapterVo;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public void deleteChapterById(String chapterId) {
        //1. 根据章节id，先删除章节下的视频
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        videoService.remove(wrapper);
        //2. 删除阿里云上的视频 TODO
        //3. 删除章节
        this.removeById(chapterId);
    }
}
